package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private CategoryMapper categoryMapper;
    /**
     * 新增菜品和对应的口味
     * @param dishDTO
     * @return
     */
    @Override
    @Transactional//保证整个方法都是原子性的，要么全部成功，要么全部失败（只要涉及多表都要加）
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //向菜品表插入一条数据
        dishMapper.insert(dish);

        //获取刚刚插入的数据的id
        Long id = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();

        //存在口味数据,开始插入
        if (flavors != null && flavors.size() > 0) {
            //为每一个口味数据赋上当前菜品的id
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(id);
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(flavors);
        }

    }


    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page=dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 菜品的批量删除
     * @param ids
     */
    @Override
    @Transactional//保证数据的一致性
    public void deleteBatch(List<Long> ids) {
        //判断当前的菜品是否能够删除（是否起售）
        for (Long id : ids) {
            Dish dish=dishMapper.selectById(id);
            if(dish.getStatus().equals(StatusConstant.ENABLE)){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //判断当前的菜品是否能够删除（是否被套餐关联）
        List<Long> setmealDishIds =setmealDishMapper.getSetmealDishIdsByDishIds(ids);
        if (setmealDishIds != null && setmealDishIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除
//        for (Long id : ids) {
//            dishMapper.deleteById(id);
//            //删除菜品关联的口味
//            dishFlavorMapper.deleteByDishId(id);
//        }
        //批量删除
        dishMapper.deleteByIdBatch(ids);
        dishFlavorMapper.deleteByDishIdsBatch(ids);
    }

    /**
     * 根据id查询菜品数据
     * @param dishId
     * @return
     */
    @Override
    public DishVO getById(Long dishId) {
        Dish dish=dishMapper.selectById(dishId);
        List<DishFlavor> dishFlavors=dishFlavorMapper.getByDishId(dishId);
        DishVO dishVO=new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 修改菜品信息
     * @param dishDTO
     * @return
     */
    @Override
    public void modify(DishDTO dishDTO) {
        log.info("Service层开始修改菜品：{}",dishDTO);
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        dishMapper.modify(dish);

        //删除原有的口味数据
        Long dishId=dish.getId();
        dishFlavorMapper.deleteByDishId(dishId);

        //重新插入新的口味数据
        List<DishFlavor> dishFlavors=dishDTO.getFlavors();
        //存在口味数据,开始插入
        if (dishFlavors != null && dishFlavors.size() > 0) {
            //为每一个口味数据赋上当前菜品的id
            dishFlavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(dishFlavors);
        }
    }

    /**
     * 菜品的启售和停售功能
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(String status, String id) {
        Dish dish=dishMapper.selectById(Long.valueOf(id));
        dish.setStatus(Integer.valueOf(status));
        dishMapper.modifyStatus(dish);
    }


    @Override
    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        log.info("业务层：{}",dish);
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            //根据菜品id查询对应的分类
            String categoryName= categoryMapper.getCategoryNameById(dish.getCategoryId());
            dishVO.setFlavors(flavors);
            dishVO.setCategoryName(categoryName);
            dishVOList.add(dishVO);
        }


        return dishVOList;
    }

}
